const express = require('express');
const COS = require('cos-nodejs-sdk-v5');
const multer = require('multer');
const router = express.Router();
const { body } = require('express-validator');
const tencentcloud = require("tencentcloud-sdk-nodejs-lke");
const LkeClient = tencentcloud.lke.v20231130.Client;
const secretId = process.env.TCADP_SECRETID; 
const secretKey = process.env.TCADP_SECRETKEY; 
const logger = require('../utils/logger');
const upload = multer();
const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey
  },
  region: "ap-guangzhou",
  profile: {
    httpProfile: {
      endpoint: "lke.tencentcloudapi.com",
    },
  },
};
const client = new LkeClient(clientConfig);
// 验证名称
const validateName = () => body('name')
  .trim()
  .notEmpty().withMessage('应用名必填');

// 验证头像
const validateAvatar = () => body('avatar')
  .trim()
  .notEmpty().withMessage('应用头像必填');

// 验证类型
const validateType = () => body('type')
  .trim()
  .notEmpty().withMessage('应用类型必填');
// 创建应用
router.post('/createApp',
  validateName(),
  validateAvatar(),
  validateType(),
  async (req, res) => {
    try {
      const bodyData = req.body;
      const params = {
        "AppType": bodyData.type,
        "BaseConfig": {
          "Name": bodyData.name,
          "Avatar": bodyData.avatar
        }
      };
      const data = await client.CreateApp(params);
      if (data && data.AppBizId) {
        res.json({
          status: 200,
          message: "应用创建成功"
        })
      } else {
        res.json({
          status: 9000,
          message: "应用创建失败"
        })
      }
    } catch (error) {
      
      res.json({
        status: 9000,
        message: "请求错误！"
      })
      logger.error(error);
    }
  }
);
// 获取应用列表
router.post("/getApp", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "AppType": "knowledge_qa",
      "PageSize": 8,
      "PageNumber": bodyData.page
    };
    const data = await client.ListApp(params);
    if (data) {
      res.json({
        status: 200,
        message: "应用列表获取成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "应用列表获取失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }

})
// 删除应用
router.post("/deleteApp", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "AppType": "knowledge_qa",
      "AppBizId": bodyData.AppBizId
    };
    const data = await client.DeleteApp(params);
    if (data) {
      res.json({
        status: 200,
        message: "应用删除成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "应用删除失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }

})
// 应用详情
router.post("/describeApp", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "AppType": "knowledge_qa",
      "AppBizId": bodyData.AppBizId,
    };
    const data = await client.DescribeApp(params);
    if (data) {
      res.json({
        status: 200,
        message: "应用调用详情",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "应用删除失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 修改应用
router.post("/modifyApp", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "AppType": "knowledge_qa",
      "AppBizId": bodyData.AppBizId,
      "BaseConfig": bodyData.BaseConfig,
      "AppConfig": bodyData.AppConfig,
    };
    const data = await client.ModifyApp(params);
    if (data) {
      res.json({
        status: 200,
        message: "应用修改成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "应用修改失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 模型列表
router.post("/listModel", async (req, res) => {
  try {
    const params = {
      "AppType": "knowledge_qa"
    };
    const data = await client.ListModel(params);
    if (data) {
      res.json({
        status: 200,
        message: "模型列表获取成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "模型列表获取失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 创建发布
router.post("/createRelease", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.AppBizId,
      "Desc": bodyData.Desc
    };
    const data = await client.CreateRelease(params);
    if (data) {
      res.json({
        status: 200,
        message: "创建发布成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "创建发布失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 发布详情
router.post("/describeRelease", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.AppBizId
    };
    const data = await client.DescribeRelease(params);
    if (data) {
      res.json({
        status: 200,
        message: "应用发布成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "应用发布失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 获取聊天记录
router.post("/getMsgRecord", async (req, res) => {
  try {
    const bodyData = req.body;
    const secrets = {
      "AppBizId": bodyData.AppBizId
    };
    const resdata = await client.GetAppSecret(secrets);
    if (resdata.AppKey) {
      const params = {
        "Type": 5,
        "Count": bodyData.count,
        "SessionId": bodyData.sessionId,
        "BotAppKey": resdata.AppKey,
      };
      try {
        const data = await client.GetMsgRecord(params);
        if (data) {
          res.json({
            status: 200,
            message: "历史记录获取成功",
            data
          })
        } else {
          res.json({
            status: 9000,
            message: "历史记录获取失败"
          })
        }
      } catch (error) {
        
        res.json({
          status: 9000,
          message: "历史记录不存在"
        })
        logger.error(error);
      }
    } else {
      res.json({
        status: 9000,
        message: "历史记录获取失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 获取文档列表
router.post("/ListDoc", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.appid,
      "PageSize": bodyData.size || 8,
      "PageNumber": bodyData.page
    };
    const data = await client.ListDoc(params);
    // console.log(data)
    if (data) {
      res.json({
        status: 200,
        message: "文档列表获取成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "文档列表获取失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }

})
// 删除文档
router.post("/DeleteDoc", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "DocBizIds": [bodyData.DocBizIds],
      "BotBizId": bodyData.BotBizId
    };
    const data = await client.DeleteDoc(params);
    // console.log(data)
    if (data) {
      res.json({
        status: 200,
        message: "文档删除成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "文档删除失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 重命名
router.post("/RenameDoc", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.BotBizId,
      "DocBizId": bodyData.DocBizId,
      "NewName": bodyData.NewName,
    };
    const data = await client.RenameDoc(params);
    // console.log(data)
    if (data) {
      res.json({
        status: 200,
        message: "文档重命名成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "文档重命名失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
// 文档预览
router.post("/GetDocPreview", async (req, res) => {
  try {
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.BotBizId,
      "DocBizId": bodyData.DocBizId
    };
    const data = await client.GetDocPreview(params);
    // console.log(data)
    if (data) {
      res.json({
        status: 200,
        message: "文档预览成功",
        data
      })
    } else {
      res.json({
        status: 9000,
        message: "文档预览失败"
      })
    }
  } catch (error) {
    
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})

// 获取文件上传临时密钥
router.post("/describeStorageCredential",upload.single('file'),async (req, res) => {
  try {
    // 文件信息在 req.file
    const file = req.file;
    const bodyData = req.body;
    const params = {
      "BotBizId": bodyData.botBizId,
      "FileType": bodyData.fileType,
      "IsPublic": bodyData.isPublic == 'true'?true:false,
      "TypeKey": bodyData.typeKey,
    };
    const resData = await client.DescribeStorageCredential(params);
    // 1. 将乱码字符串转换为 Buffer（假设它是 UTF-8 编码）
    const buffer = Buffer.from(file.originalname, 'binary'); // 或 'latin1'
    // 2. 用 UTF-8 解码 Buffer
    const correctName = buffer.toString('utf8');
    const ext = correctName.split('.').pop();
    const cosInstance = new COS({
      getAuthorization: (options, callback) => {
        callback({
          TmpSecretId: resData.Credentials.TmpSecretId,        
          TmpSecretKey: resData.Credentials.TmpSecretKey,      
          SecurityToken: resData.Credentials.Token, 
          StartTime: resData.StartTime, 
          ExpiredTime: resData.ExpiredTime, 
        });
      }
    });
    cosInstance.putObject(
      {
        Bucket: resData.Bucket,
        Region: resData.Region,
        Key: resData.UploadPath,
        Body: file.buffer,
        ContentLength: file.size,
      }, async (err, data) => {
        if (err) {
          res.json({
            status: 9000,
            message: "文件上传到cos错误！"
          })
          logger.error(err);
        }else{
          if (data) {
            const newData = data;
            // console.log(resData,data,'hkwegwefhgehgegfwjeg')
            newData.UploadPath = resData.UploadPath
            newData.Bucket = resData.Bucket
            newData.cosHash = data.headers['x-cos-hash-crc64ecma']
            res.json({
              status: 200,
              message: "获取文件上传临时密钥成功",
              data:newData
            })
          } else {
            res.json({
              status: 9000,
              message: "获取文件上传临时密钥失败"
            })
          }
        }
      }
    );
  } catch (error) {
    res.json({
      status: 9000,
      message: "请求错误！"
    })
    logger.error(error);
  }
})
module.exports = router;